/*
Copyright (c) 2009  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.tools;

import fschmidt.util.java.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;


public final class TcpProxy {
	private static final Logger logger = LoggerFactory.getLogger(TcpProxy.class);

	private static final Executor exec = Executors.newCachedThreadPool();

	// never returns
	public static void proxy(SocketAddress from,final SocketAddress to) throws IOException {
		final ServerSocket server = new ServerSocket();
		server.bind(from);
		while(true) {
			final Socket client = server.accept();
			exec.execute(new Runnable(){public void run() {
				final Socket proxy = new Socket();
				try {
					proxy.connect(to);
					exec.execute(new Runnable(){public void run() {
						try {
							IoUtils.copyAll( proxy.getInputStream(), client.getOutputStream() );
						} catch(IOException e) {
							logger.debug("",e);
						}
					}});
					IoUtils.copyAll( client.getInputStream(), proxy.getOutputStream() );
				} catch(IOException e) {
					logger.debug("",e);
				} finally {
					try {
						proxy.close();
					} catch(IOException e) {}
					try {
						client.close();
					} catch(IOException e) {}
				}
			}});
		}
	}

	private static SocketAddress parseSocketAddress(String s) {
		String[] a = s.split(":");
		return new InetSocketAddress( a[0], Integer.parseInt(a[1]) );
	}

	public static void proxy(String from,String to) throws IOException {
		proxy(parseSocketAddress(from), parseSocketAddress(to));
	}

	// better to write your own main()
	public static void main(String[] args) throws IOException {
		org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.INFO);
		org.apache.log4j.BasicConfigurator.configure();
		proxy(args[0], args[1]);
	}

}
